package com.huatai.vba.finrecon.quartz;

import java.util.Date;
import java.util.List;

import com.huatai.vba.common.utils.CalendarUtil;
import com.huatai.vba.common.utils.ListUtils;
import com.huatai.vba.dal.model.VbaFileTask;
import com.huatai.vba.dal.model.VbaFileTaskRecord;

/**
 * 自动 创建任务批次
 * 
 * @author fanrui16
 *
 */
// @Component
public class AutoCreateRecordTaskAction extends AbstractTaskAction {

	// @Scheduled(cron = "0 0 * * * ?")
	public void execute() throws Exception {

		/**
		 * 获取自然日期
		 */
		String operDate = CalendarUtil.getStrDate(System.currentTimeMillis(), CalendarUtil.FORMAT4);

		// 判断当前时间是否在批次执行允许时间内

		List<VbaFileTask> vbaFileTasks = vbaFileTaskService.getByFirPm(operDate);
		if (ListUtils.isEmpty(vbaFileTasks))
			return;
		for (VbaFileTask vba : vbaFileTasks) {

			VbaFileTaskRecord record = vbaFileTaskRecordService.queryVbaFileTaskRecord(operDate, vba.getTaskId());
			if (record != null)
				continue;

			/**
			 * 获取自然时间
			 */
			String sCurTime = CalendarUtil.getStrDate(System.currentTimeMillis(), CalendarUtil.HHMMSS);

			String taskStartTime = vba.getTaskStartTime();
			String taskEndTime = vba.getTaskEndTime();

			String taskNextDate = vba.getTaskNextDate();

			/**
			 * 判断执行时间是否在区间中，执行日期是否是
			 */
			if ((CalendarUtil.compareDate(taskStartTime, sCurTime, CalendarUtil.HHMMSS) <= 0
					&& CalendarUtil.compareDate(taskEndTime, sCurTime, CalendarUtil.HHMMSS) >= 0
					&& CalendarUtil.compareDate(operDate, taskNextDate, CalendarUtil.FORMAT4) > 0)) {
				logger.info("创建批次号失败,未在配置时间范围内执行");
				continue;
			}

			if (!Boolean.valueOf(vba.getIsExeHoliday()) && this.isHoliday(operDate)) {
				logger.info("创建批次号失败,节假日配置不执行");
				continue;
			}

			String strNextCheckDate = null;
			do {
				Date currentDate = CalendarUtil.parseFormatDateByFormat(operDate, CalendarUtil.YYYYMMDD);
				Date nextDate = CalendarUtil.addDate(currentDate, 1);
				strNextCheckDate = CalendarUtil.getStrDate(nextDate.getTime(), CalendarUtil.YYYYMMDD);
				// 当配置了节假日不执行时， 顺延到下一个工作日
			} while (!Boolean.valueOf(vba.getIsExeHoliday()) && this.isHoliday(strNextCheckDate));

			Integer iCount = vbaFileTaskService.updateNextCheckDateByIdAndOldDate(vba.getTaskId(), operDate,
					strNextCheckDate);
			if (iCount != 0) {
				logger.info("批次已完成");
				continue;
			}

			record = new VbaFileTaskRecord();
			record.setTaskId(vba.getTaskId());
			record.setOccurDate(operDate);
			// insert
		}
	}

}
